import 'dart:convert';
import 'dart:io';

import 'package:dio/dio.dart';
import 'package:logger/logger.dart';

class NWLogginInterceptor extends Interceptor {
  @override
  void onError(DioException err, ErrorInterceptorHandler handler) {
    if (err.response != null) {
      logDebug(
          "<-- ERROR ${err.response?.statusCode} ${err.response?.requestOptions.method} ${err.response?.requestOptions.baseUrl}${err.response?.requestOptions.path}");
    } else {
      logDebug(
          "--> ERROR ${err.requestOptions.method} ${err.requestOptions.baseUrl}${err.requestOptions.path}");
    }
    if (err.error != null) {
      var socketErr = err.error as SocketException;
      logDebug("<-- SocketError message: ${socketErr.message}");
      if (socketErr.osError != null) {
        logDebug(
            "<-- OSError message: ${socketErr.osError!.message}, code: ${socketErr.osError!.errorCode}");
      }
    } else {
      logDebug("<-- DioError message: ${err.message}");
    }

    logDebug("<-- END HTTP");
    super.onError(err, handler);
  }

  @override
  void onRequest(RequestOptions options, RequestInterceptorHandler handler) {
    logDebug("--> HTTP ${options.method} ${options.baseUrl}${options.path}");
    logDebug("Content Type: ${options.contentType}");
    logDebug("Authorization: ${options.headers["Authorization"]}");
    logDebug("Headers: ${options.headers}");
    logDebug("Parameters: ${options.queryParameters}");
    logDebug("body: ${options.data}");
    logDebug("--> Sended ${options.method} ${options.baseUrl}${options.path}");
    super.onRequest(options, handler);
  }

  @override
  void onResponse(Response response, ResponseInterceptorHandler handler) {
    logDebug(
        "<-- ${response.statusCode} ${response.requestOptions.method} ${response.requestOptions.baseUrl}${response.requestOptions.path}");
    try {
      String responseAsString = json.encode(response.data);
      logDebug(responseAsString);
    } catch (_) {
      logDebug(response.data);
    }
    logDebug("<-- END HTTP ${response.statusCode} ${response.requestOptions.method} ${response.requestOptions.baseUrl}${response.requestOptions.path}");
    super.onResponse(response, handler);
  }
}

const bool production = bool.fromEnvironment("dart.vm.product");

logDebug(Object? obj) {
  if (!production) {
    print(obj);
  }
}

logErr(Object? obj) {
  print(obj);
}

class loggin {
  static final _logger =
      Logger(output: FileOutput(file: File("./networking.log")));
  static v(String message) {
    _logger.v(message);
  }

  static d(String message) {
    _logger.d(message);
  }

  static i(String message) {
    _logger.i(message);
  }

  static w(String message) {
    _logger.w(message);
  }

  static e(String message) {
    _logger.e(message);
  }

  static wtf(String message) {
    _logger.wtf(message);
  }

  
}
